 #!/usr/bin/env bash
# ==============================================================================
# What:
# - transfers local site's muRIFCS file ($SCP_SOURCE) to the specified location
#   on the remote server ($SCP_DEST)
# - uses key based SCP transfer
# ==============================================================================
export SELF=${0##*/}
export BASE_DIR=${BASE_DIR:-"$( cd "$( dirname "$0" )" && pwd )"}
source ${BASE_DIR}/local2rdr.profile

# Configurable parameters
# - uses definitions from local2rdr.profile by default
export SCP_SOURCE=${TRANSFER_RIFCS_INPUT}
export SCP_USER=${TRANSFER_RIFCS_SCP_USER}
export SCP_DEST_HOST=${TRANSFER_RIFCS_SCP_DEST_HOST}
export SCP_DEST_PORT=${TRANSFER_RIFCS_SCP_DEST_PORT}
export SCP_DEST_DIR=${TRANSFER_RIFCS_SCP_DEST_DIR}

# Shouldn't need to change
export SCP_DEST=${SCP_USER}@${SCP_DEST_HOST}:${SCP_DEST_DIR}

# Debug info: prints all internal environment variables on request
if [[ $debug_transferRIFCS = "true" ]]
then
    echo
    echo "== ${SELF} core variables   =="
    echo "BASE_DIR     : ${BASE_DIR}"
    echo "SCRATCH_DIR  : ${SCRATCH_DIR}"
    echo "AUTH_DIR     : ${AUTH_DIR}"
    echo "== ${SELF} script variables =="
    echo "RSA_KEY      : ${RSA_KEY}"
    echo "SCP_SOURCE   : ${SCP_SOURCE}"
    echo "SCP_USER     : ${SCP_USER}"
    echo "SCP_DEST_HOST: ${SCP_DEST_HOST}"
    echo "SCP_DEST_DIR : ${SCP_DEST_DIR}"
    echo "SCP_DEST     : ${SCP_DEST}"
    echo
fi


echo
echo "  executing ${SELF} ..."

if [[ ! -e ${RSA_KEY} ]]
then
   echo "  error: missing RSA key: ${RSA_KEY}"
   echo "  you can generate one by running:"
   echo
   echo "    $ [[ -e ${AUTH_DIR} ]] || mkdir ${AUTH_DIR}"
   echo "    $ ssh-keygen -b 4096 -t rsa -f ${RSA_KEY}"
   echo
   echo "  then send ${RSA_KEY}.pub"
   echo "  to the sys admin of ${SCP_DEST_HOST}"
   echo "  before running the script again"
   echo
   exit 1
elif [[ ! -e ${SCP_SOURCE} ]]
then
   echo "  error: missing input file: ${SCP_SOURCE}"
   echo
   exit 1
else 
   scp -q -i ${RSA_KEY} -P ${SCP_DEST_PORT} ${SCP_SOURCE} ${SCP_DEST}

   if [[ $? = 0 ]]
   then
      echo "  finished: completed transfer of"
      echo "    ${SCP_SOURCE}"
      echo "   to"
      echo "    ${SCP_DEST}"
      echo
      exit 0
   else
      echo "  failure: some error occurred"
      echo
      exit 1
   fi
fi